<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input v-model="params.name" style="width: 200px" placeholder="请输入商品名称"></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="findBySearch()">查询</el-button>
      <el-button type="warning" style="margin-left: 10px" @click="reset()">清空</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" >
        <el-table-column label="卖家id" prop="sellerId" v-if="user.role ==='boss'"></el-table-column>
        <el-table-column label="卖家姓名" prop="sellerName" v-if="user.role ==='boss'"></el-table-column>
        <el-table-column prop="commodityName" label="商品名称"></el-table-column>
        <el-table-column prop="userName" label="购买人"></el-table-column>
        <el-table-column prop="time" label="购买时间"></el-table-column>
        <el-table-column prop="area" label="地址"></el-table-column>
        <el-table-column prop="telephone" label="联系电话"></el-table-column>
        <el-table-column prop="description" label="订单要求"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button slot="reference" type="primary" style="margin-left: 5px" @click="startchat(scope.row)">聊天</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px" v-if="user.role === 'ROLE_ADMIN'">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-dialog :visible.sync="dialogchatFormVisible" title="开始聊天吧" style="width: 1900px" :center="true">
        <el-row>
          <el-col :span="20">
            <div style="width: 800px; margin: 0 auto; background-color: white; border-radius: 5px; box-shadow: 0 0 10px #ccc; margin-left: 51px;margin-bottom: 20px">
              <!-- 聊天室内容 -->
              <div style="text-align: center; line-height: 50px;">
                {{ chatUser }}
              </div>
              <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
              <div style="height: 200px">
                <textarea v-model="text" style="height: 160px; width: 100%; padding: 20px; border: none; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; outline: none"></textarea>
                <div style="text-align: right; padding-right: 10px">
                  <el-button type="primary" size="mini" @click="send">发送</el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-dialog>
    </div>
    <div style="margin-top: 10px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

let socket;
export default {
  data() {
    return {
      params: {
        name: '',
        seller: '',
        sellerName:'',
        pageNum: 1,
        pageSize: 5,
      },
      tableData: [],
      total: 0,
      dialogFormVisible: false,
      dialogchatFormVisible:false,
      form: {},
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
      isCollapse: false,
      text: "",
      messages: [],
      content: '',
      chatUser:'',
      User:{},
      Users:[],
      userName:'',

    }
  },
  // 页面加载的时候，做一些事情，在created里面
  created() {
    this.findBySearch();
  },
  // 定义一些页面上控件出发的事件调用的方法
  methods: {
    findBySearch() {
      request.get("/reserve/search", {
        params: this.params
      }).then(res => {
        if (res.code === '0') {
          this.tableData = res.data.list;
          this.total = res.data.total;
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    add() {
      this.form = {};
      this.dialogFormVisible = true;
    },
    edit(obj) {
      this.form = obj;
      this.dialogFormVisible = true;
    },
    reset() {
      this.params = {
        pageNum: 1,
        pageSize: 5,
        name: '',
        phone: ''
      }
      this.findBySearch();
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.findBySearch();
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum;
      this.findBySearch();
    },
    del(id) {
      request.delete("/reserve/" + id).then(res => {
        if (res.code === '0') {
          this.$message.success("删除成功");
          this.findBySearch();
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    startchat(row){
      if (this.user.name === row.sellerName)
      {
        this.chatUser = row.userName;
      }else{
        this.chatUser = row.sellerName;
      }
      this.init();
      this.dialogchatFormVisible = true;


    },
    send(){
      if (!this.chatUser) {
        this.$message({type: 'warning', message: "请选择聊天对象"})
        return;
      }
      if (!this.text) {
        this.$message({type: 'warning', message: "请输入内容"})
      } else {
        if (typeof (WebSocket) == "undefined") {
          console.log("您的浏览器不支持WebSocket");
        } else {
          console.log("您的浏览器支持WebSocket");
          // 组装待发送的消息 json
          // {"from": "zhang", "to": "admin", "text": "聊天文本"}
          let message = {from: this.user.name, to: this.chatUser, text: this.text}
          socket.sen
          socket.send(JSON.stringify(message));  // 将组装好的json发送给服务端，由服务端进行转发
          this.messages.push({user: this.user.name, text: this.text})
          // 构建消息内容，本人消息
          this.createContent(null, this.user.name, this.text)
          this.text = '';
        }
      }
    },
    createContent(remoteUser, nowUser, text) {  // 这个方法是用来将 json的聊天消息数据转换成 html的。
      let html
      // 当前用户消息
      if (nowUser) {
        html = `
      <div class="el-row" style="padding: 5px 0">
        <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
          <div class="tip left">
            <span style="font-weight: bold;">${text}</span>
          </div>
        </div>
        <div class="el-col el-col-2">
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
          </span>
        </div>
      </div>`;
      } else if (remoteUser) {
        html = `
      <div class="el-row" style="padding: 5px 0">
        <div class="el-col el-col-2" style="text-align: right">
          <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
            <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
          </span>
        </div>
        <div class="el-col el-col-22" style="text-align: left; padding-left: 10px">
          <div class="tip right">
            <span style="font-weight: bold;"> ${text}</span>
          </div>
        </div>
      </div>`;
      }
      console.log(html)
      this.content += html;
    },
    init() {
      let username = this.user.name;
      console.log(this.user.name)
      let _this = this;
      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        let socketUrl = "ws://localhost:8081/imserver/" + username;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        //打开事件
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data)
          let data = JSON.parse(msg.data)  // 对收到的json数据进行解析， 类似这样的： {"users": [{"username": "zhang"},{ "username": "admin"}]}
          if (data.users) {  // 获取在线人员信息
            _this.users = data.users.filter(user => user.name !== username)  // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
          } else {
            // 如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {"from": "zhang", "text": "hello"}
            if (data.from === _this.chatUser) {
              _this.messages.push(data)
              // 构建消息内容
              _this.createContent(data.from, null, data.text)
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        }
      }
    }
  }
}
</script>
<style scoped>
.bubble {
  background-color: #5cb85c;
  color: #fff;
  padding: 8px;
  border-radius: 8px;
  max-width: 70%;
  word-wrap: break-word;

  /* 新增样式以垂直居中文本 */
  display: flex;
  align-items: center;
}

.left-bubble {
  align-self: flex-end;
}

.right-bubble {
  align-self: flex-start;
}
</style>
